//
//  PhotoViewerCell.swift
//  weibo117
//
//  Created by 宋禹奇 on 15/7/10.
//  Copyright © 2015年 宋禹奇. All rights reserved.
//

import UIKit
import SDWebImage

class PhotoViewerCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            imageView.sd_setImageWithURL(imageURL!, placeholderImage: nil) { (image, error, _, _) in
                //下载完毕之后,设置图片的大小
                self.imagePostion(image)
            }
        
        }
    }
    //根据尺寸计算位置
    private func imagePostion(image: UIImage) {
        
        let size = displaySize(image)
        
        
        //判断是否是长图
        if bounds.height < size.height { //长图
            imageView.frame = CGRect(origin: CGPointZero, size: size)
        
        }else { //短图
            let y = (bounds.height - size.height) * 0.5
            imageView.frame = CGRect(x: 0, y: y, width: size.width, height: size.height)
        }
    
    }
    
    
    //根据图像计算尺寸
    private func displaySize(image: UIImage) -> CGSize {
    
        let scale = image.size.height / image.size.width
        
        let h = bounds.width * scale
    
        return CGSize(width: bounds.width, height: h)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        scrollView.frame = bounds
        addSubview(scrollView)
        scrollView.addSubview(imageView)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //懒加载控件
    lazy private var scrollView = UIScrollView()
    lazy private var imageView = UIImageView()
    
}
